//
//  UpdateOldPhoneViewController.m
//  ShowYork
//
//  Created by hxh on 2020/10/13.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "UpdateOldPhoneViewController.h"
#import "ChangeNewPhoneViewController.h"
#import "HWTFCursorView.h"
@interface UpdateOldPhoneViewController ()<HWTFCursorViewDelegate>
@property (nonatomic,strong)UILabel *mainTitleLb;
@property (nonatomic,strong)UILabel *phoneTitleLb;
@property (nonatomic,strong)UIButton *sendBtn;
@property (nonatomic,strong)UIButton *nextBtn;
@property (nonatomic,strong)HWTFCursorView *cursorView;
@end

@implementation UpdateOldPhoneViewController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = YES;

    [IQKeyboardManager sharedManager].enable = NO;
  
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    blackLineImageView.hidden = NO;
    

    [IQKeyboardManager sharedManager].enable = YES;

}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationFade;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    // Do any additional setup after loading the view.
}




- (void)setUI{
    
    self.mainTitleLb = [[UILabel alloc]init];
    self.mainTitleLb.text = @"验证当前手机号";
    self.mainTitleLb.textColor = RGBA(35, 24, 21, 1);
    self.mainTitleLb.font = [UIFont boldSystemFontOfSize:26];
    [self.view addSubview:self.mainTitleLb];
    [self.mainTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(16 + GK_STATUSBAR_HEIGHT);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left).offset(24);
    }];
    
    self.phoneTitleLb = [[UILabel alloc]init];
    self.phoneTitleLb.text = self.phoneStr;
    self.phoneTitleLb.textColor = C51;
    self.phoneTitleLb.font = font(14);
    [self.view addSubview:self.phoneTitleLb];
    [self.phoneTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainTitleLb.mas_bottom).offset(2);
        make.left.equalTo(self.mainTitleLb);
    }];
    
    NSString *string = [self.phoneTitleLb.text substringWithRange:NSMakeRange(3,4)];
     //字符串的替换
     self.phoneTitleLb.text = [self.phoneTitleLb.text stringByReplacingOccurrencesOfString:string withString:@"****" options:0 range:NSMakeRange(3, 4)];
    
    self.sendBtn = [[UIButton alloc]init];
    [self.sendBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.sendBtn setTitleColor:[RPAppManager themColor] forState:UIControlStateNormal];
    [self.sendBtn setTitleColor:C153 forState:UIControlStateDisabled];
    self.sendBtn.titleLabel.font = font(14);
    self.sendBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.sendBtn addTarget:self action:@selector(sendMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sendBtn];
    
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.phoneTitleLb);
        make.right.equalTo(self.view).offset(-24);
        make.width.mas_equalTo(100);
    }];
    
    self.cursorView = [[HWTFCursorView alloc]initWithCount:6 margin:0];
    self.cursorView.delegate = self;


    [self.view addSubview:self.cursorView];

    [self.cursorView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(24);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-24);
        }else{
            make.left.equalTo(self.view.mas_left).offset(24);
            make.right.equalTo(self.view.mas_right).offset(-24);
        }
        make.top.equalTo(self.phoneTitleLb.mas_bottom).offset(40);
        make.height.mas_equalTo(44);
    }];
    
    [self.cursorView startEditing];
 
    self.nextBtn = [[UIButton alloc]init];
    self.nextBtn.layer.cornerRadius = 22;
    self.nextBtn.layer.masksToBounds = YES;
    [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [self.nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.nextBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateDisabled];
    [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_selected_tag"] forState:UIControlStateNormal];
    [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"login_confirm_normal_tag"] forState:UIControlStateDisabled];;
    [self.nextBtn addTarget:self action:@selector(nextMethod) forControlEvents:UIControlEventTouchUpInside];
    self.nextBtn.enabled = NO;
    [self.view addSubview:self.nextBtn];
    
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cursorView.mas_bottom).offset(50);
        make.left.equalTo(self.view).offset(24);
        make.right.equalTo(self.view).offset(-24);
        make.height.mas_equalTo(44);
    }];
    
}

- (void)nextMethod{

    [SVProgressHUD show];

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = self.phoneStr;
    param[@"code"] = self.cursorView.code;
    param[@"md5"] = [RPAppManager md5StrWithApi:OnlyValidCode];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(OnlyValidCode) parames:param success:^(id responseObj) {

        ChangeNewPhoneViewController *nextVC = [[ChangeNewPhoneViewController alloc]initWithOldPhone:self.phoneStr oldCode:self.cursorView.code];
        [self.navigationController pushViewController:nextVC animated:YES];
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (void)sendMethod{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"oldPhone"] = self.phoneStr;
    param[@"newPhone"] = self.phoneStr;
    param[@"id"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:ChangePhoneAndSendCode];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(ChangePhoneAndSendCode) parames:param success:^(id responseObj) {
       
        __block NSInteger time = 59;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(timer, ^{
            if (time <= 0) {
                dispatch_source_cancel(timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.sendBtn.enabled = YES;
                    [self.sendBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                });
            }else{
                int seconds = time % 60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.sendBtn setTitle:[NSString stringWithFormat:@"%.2d秒",seconds] forState:UIControlStateDisabled];
                    self.sendBtn.enabled = NO;
                });
                time--;
            }
        });
        dispatch_resume(timer);
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark - HWTFCursorViewDelegate
- (void)completeCodeWithStatus:(BOOL)isComplete{
    if (isComplete) {
        self.nextBtn.enabled = YES;
    }else{
        self.nextBtn.enabled = NO;
    }
    
}

@end
